<!-- src/views/EmailBinding.vue -->
<template>
  <div>
   
    <Card>
      <CardHeader>
        <CardTitle class="text-2xl font-bold tracking-tight">
            绑定的邮箱
      </CardTitle>
        <CardDescription class="text-muted-foreground">
          邮箱是您身份的重要凭证。当账号发生异常时，将会通过该邮箱第一时间通知到您
        </CardDescription>
      </CardHeader>
      <CardContent>
        <p v-if="currentEmail" class="text-lg">
          {{ currentEmail }}
          <Button
            variant="outline"
            size="sm"
            class="ml-2"
            @click="startChangeEmail"
          >
            更换邮箱
          </Button>
        </p>
        <p v-else class="text-lg text-gray-500">暂未绑定邮箱</p>
      </CardContent>
    </Card>

    <Card class="mt-6" v-if="showEmailForm">
      <CardHeader>
        <CardTitle>{{ currentEmail ? "更换邮箱" : "绑定新邮箱" }}</CardTitle>
      </CardHeader>
      <CardContent>
        <form @submit.prevent="handleSubmit" class="space-y-4">
          <div>
            <Label for="email">新邮箱地址</Label>
            <Input
              id="email"
              v-model="newEmail"
              type="email"
              placeholder="请输入新的邮箱地址"
              required
            />
          </div>
          <div class="flex space-x-2">
            <Input v-model="verificationCode" placeholder="验证码" />
            <Button
              type="button"
              @click="sendVerificationCode"
              :disabled="cooldown > 0"
            >
              {{ cooldown > 0 ? `${cooldown}s后重试` : "发送验证码" }}
            </Button>
          </div>
          <Button type="submit">确认绑定</Button>
        </form>
      </CardContent>
    </Card>
  </div>
</template>

<script setup lang="ts">
import { ref } from "vue";
import {
  Card,
  CardHeader,
  CardTitle,
  CardContent,
  CardDescription
} from '@/components/ui/card'

import { Label } from '@/components/ui/label'
import { Input } from '@/components/ui/input'
import { Button } from '@/components/ui/button'

const currentEmail = ref("user@example.com"); // 假设这是当前绑定的邮箱
const showEmailForm = ref(false);
const newEmail = ref("");
const verificationCode = ref("");
const cooldown = ref(0);

const startChangeEmail = () => {
  showEmailForm.value = true;
  newEmail.value = "";
  verificationCode.value = "";
};

const sendVerificationCode = () => {
  // 这里应该调用后端 API 来发送验证码
  console.log("Sending verification code to:", newEmail.value);
  cooldown.value = 60;
  const timer = setInterval(() => {
    cooldown.value--;
    if (cooldown.value === 0) {
      clearInterval(timer);
    }
  }, 1000);
};

const handleSubmit = () => {
  // 这里应该调用后端 API 来验证和更新邮箱
  console.log(
    "Submitting new email:",
    newEmail.value,
    "with code:",
    verificationCode.value,
  );
  // 假设绑定成功
  currentEmail.value = newEmail.value;
  showEmailForm.value = false;
  // 重置表单
  newEmail.value = "";
  verificationCode.value = "";
};
</script>
